<template>
  <div class="puzzle-game">
    <header class="game-header glass">
      <el-button @click="$router.back()" text><el-icon><ArrowLeft /></el-icon>返回</el-button>
      <div class="score-board">
        <span>得分: {{ score }}</span>
        <span>进度: {{ currentWordIndex + 1 }}/{{ totalWords }}</span>
      </div>
    </header>

    <div class="game-content" v-if="currentWord && !gameOver">
      <div class="hint glass">
        <h3>中文提示</h3>
        <p>{{ currentWord.chinese }}</p>
      </div>

      <div class="puzzle-area glass">
        <div class="answer-slots">
          <div 
            v-for="(letter, index) in answer"
            :key="index"
            class="slot"
            :class="{ filled: letter }"
          >
            {{ letter || '_' }}
          </div>
        </div>

        <div class="letter-tiles">
          <div 
            v-for="(letter, index) in shuffledLetters"
            :key="index"
            class="tile"
            :class="{ used: usedIndices.includes(index) }"
            @click="selectLetter(letter, index)"
          >
            {{ letter }}
          </div>
        </div>

        <div class="actions">
          <el-button @click="clearAnswer">清空</el-button>
          <el-button type="primary" @click="checkAnswer">提交答案</el-button>
          <el-button type="warning" @click="skipWord">跳过(-5分)</el-button>
        </div>
      </div>
    </div>

    <div class="game-over glass" v-else-if="gameOver">
      <h2>🎉 完成！</h2>
      <p>得分: {{ score }}</p>
      <p>正确: {{ correctCount }}/{{ totalWords }}</p>
      <el-button type="primary" size="large" @click="restart">再玩一次</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { gameApi } from '@/api/game'

const emit = defineEmits(['finish'])

const words = ref<any[]>([])
const currentWordIndex = ref(0)
const answer = ref<string[]>([])
const shuffledLetters = ref<string[]>([])
const usedIndices = ref<number[]>([])
const score = ref(0)
const correctCount = ref(0)
const gameOver = ref(false)
const totalWords = ref(10)

const currentWord = computed(() => words.value[currentWordIndex.value])

const loadWords = async () => {
  try {
    const route = useRoute()
    const difficulty = route.query.difficulty || 'hard'
    
    const res = await gameApi.getRandomWords({ count: 10, difficulty: difficulty as string })
    if (res.success && res.data) {
      words.value = res.data
      setupWord()
    }
  } catch (error) {
    console.error('加载单词失败:', error)
    ElMessage.error('加载单词失败')
  }
}

const setupWord = () => {
  if (!currentWord.value) {
    finishGame()
    return
  }
  
  answer.value = new Array(currentWord.value.word.length).fill('')
  const letters = currentWord.value.word.split('')
  shuffledLetters.value = [...letters].sort(() => Math.random() - 0.5)
  usedIndices.value = []
}

const selectLetter = (letter: string, index: number) => {
  if (usedIndices.value.includes(index)) return
  
  const emptyIndex = answer.value.findIndex(l => l === '')
  if (emptyIndex !== -1) {
    answer.value[emptyIndex] = letter
    usedIndices.value.push(index)
  }
}

const clearAnswer = () => {
  answer.value = new Array(currentWord.value.word.length).fill('')
  usedIndices.value = []
}

const checkAnswer = () => {
  const userAnswer = answer.value.join('').toLowerCase()
  const correctAnswer = currentWord.value.word.toLowerCase()
  
  if (userAnswer === correctAnswer) {
    score.value += 15
    correctCount.value++
    ElMessage.success('正确！+15分')
    nextWord()
  } else {
    ElMessage.error('答案错误，再试一次')
  }
}

const skipWord = () => {
  score.value = Math.max(0, score.value - 5)
  ElMessage.warning('跳过 -5分')
  nextWord()
}

const nextWord = () => {
  currentWordIndex.value++
  if (currentWordIndex.value >= words.value.length) {
    finishGame()
  } else {
    setupWord()
  }
}

const finishGame = () => {
  gameOver.value = true
  emit('finish', score.value, correctCount.value)
}

const restart = () => {
  currentWordIndex.value = 0
  score.value = 0
  correctCount.value = 0
  gameOver.value = false
  loadWords()
}

onMounted(() => {
  loadWords()
})
</script>

<style scoped lang="scss">
.puzzle-game {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  margin-bottom: 30px;
  
  .score-board {
    display: flex;
    gap: 30px;
    color: white;
    font-size: 1.2rem;
    font-weight: bold;
  }
}

.game-content {
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.hint {
  padding: 30px;
  text-align: center;
  
  h3 {
    color: white;
    font-size: 1.5rem;
    margin-bottom: 15px;
  }
  
  p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 2rem;
    font-weight: bold;
  }
}

.puzzle-area {
  padding: 40px;
  
  .answer-slots {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-bottom: 40px;
    
    .slot {
      width: 50px;
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 2rem;
      font-weight: bold;
      color: white;
      border-bottom: 3px solid rgba(255, 255, 255, 0.5);
      
      &.filled {
        border-bottom-color: #67c23a;
      }
    }
  }
  
  .letter-tiles {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;
    margin-bottom: 30px;
    
    .tile {
      width: 50px;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.5rem;
      font-weight: bold;
      color: white;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 10px;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover:not(.used) {
        transform: scale(1.1);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.5);
      }
      
      &.used {
        opacity: 0.3;
        cursor: not-allowed;
      }
    }
  }
  
  .actions {
    display: flex;
    justify-content: center;
    gap: 15px;
  }
}

.game-over {
  max-width: 500px;
  margin: 100px auto;
  padding: 60px;
  text-align: center;
  
  h2 {
    color: white;
    font-size: 2.5rem;
    margin-bottom: 30px;
  }
  
  p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1.3rem;
    margin: 15px 0;
  }
}
</style>

